<template>
  <div class="container">
    <div class="concreteBoard">
      <div class="item-content">
        <p>
          <span style="font-size: 25px; color: #021148">审批信息</span>
        </p>
        <p>
          <span style="font-size: 18px; color: #021148">审批类型名:</span>
          <el-input class="el-style" v-model="typeName" @input="typeNameValue" placeholder="Please input" />
        </p>
        <p style="margin: 1.5%">
          <span style="font-size: 18px; color: #021148">固定审批项:</span>
        </p>
        <el-table :data="fixedItems" style="width: 80%; border-radius: 10px" height="200px">
          <el-table-column label="审批项名称">
            <template #default="scope">{{ scope.row }}</template>
          </el-table-column>
        </el-table>
        <p style="margin: 1.5%">
          <span style="font-size: 18px; color: #021148">流动审批项:</span>
        </p>
        <p style="margin: 1.5%">
          <el-button type="primary" @click="addProcessItems">增添审批项</el-button>
          <el-select v-model="processItems" multiple filterable allow-create default-first-option
            :reserve-keyword="false" placeholder="Choose items for your process" class="el-style">
            <el-option v-for="(item, index) in processOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </p>
        <el-table :data="selectedItems" style="width: 80%; border-radius: 10px" height="200px">
          <el-table-column label="审批项名称">
            <template #default="scope">{{ scope.row }}</template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <!-- 之后有机会再做优化 -->
              <!-- <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                编辑
              </el-button>-->
              <el-button size="small" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="item-timestamp">
        <p>
          <span style="font-size: 25px; color: #021148">审批流程</span>
        </p>
        <p>
          <span style="font-size: 18px; color: #021148">待增加审核节点信息</span>
        </p>
        <p>
          <span style="font-size: 16px; color: #021148">节点名称</span>
          <el-input v-model="nodeName" @input="nodeNameValue" class="el-style" placeholder="Please input" />
        </p>
        <p>
          <span style="font-size: 16px; color: #021148">节点所处顺序</span>
          <el-input-number class="el-style" v-model="nodePriority" :min="1" />
        </p>
        <p>
          <span style="font-size: 16px; color: #021148">此节点是否需要部门审核</span>
          <el-radio-group class="el-style" v-model="isWithDept">
            <el-radio value="0" size="large">是</el-radio>
            <el-radio value="1" size="large">否</el-radio>
          </el-radio-group>
        </p>
        <p v-if="isWithDept === '0'">
          <span style="font-size: 16px; color: #021148">此节点到上几级部门审核</span>
          <el-input-number class="el-style" v-model="deptId" :min="0" :max="deptLayers" />
        </p>
        <p>
          <el-button @click="addProcessNode" type="primary">增加审批节点</el-button>
        </p>
        <p>
          <span style="font-size: 18px; color: #021148">删除审核节点</span>
        </p>
        <p>
          <el-button @click="deleteProcessNode" type="danger">删除审批节点</el-button>
          <el-select v-model="readyForDelete" placeholder="Choose tags for your article" class="el-style">
            <el-option v-for="(item, index) in processNodes" :key="index"
              :label="'第' + item.nodePriority + '步 ' + item.nodeName" :value="item.nodePriority" />
          </el-select>
        </p>
        <el-timeline style="max-width: 30vw">
          <el-timeline-item v-for="(item, index) in processNodes" :key="index">
            <span>{{ item.nodeName }}</span>
            <span style="color: #b7b7b7;"> 此节点所处顺序：{{ item.nodePriority }}</span>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
    <div class="item-button">
      <el-button @click="store" style="margin: 2%; width: 45%" type="primary">保存</el-button>
      <el-button @click="reset" style="margin: 2%; width: 45%" type="default">重置</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { ca, de } from "element-plus/es/locale";
import { computed, onMounted, ref, toRaw, watch } from "vue";
import { getTreeHeight } from "../../api/dept.js";
import { addType } from "../../api/process.js";

//种类名称
const typeName = ref("");
//待输入的审批项
const processItems = ref<string[]>([]);
//可选择的审批项,从数据库拿过来的，要做处理的
const processOptions = ref<string[]>([]);
//已经被选中的审批项
const selectedItems = ref<string[]>([]);
const fixedItems = [
  "申请人姓名",
  "申请人工号",
  "申请人部门名称",
  "申请人职称"
]

interface processNode {
  nodeName: string;
  isWithDept: boolean;
  deptPriority: number;
  nodePriority: number;
}
//节点名称
const nodeName = ref("");
//节点优先级
const nodePriority = ref(0);
//是否需要部门审核
const isWithDept = ref("1");
//部门级别
const deptId = ref(0);
//一批审批节点
const processNodes = ref<processNode[]>([]);

//缓存的审批节点
const cacheProcessNode = ref<processNode>({
  nodeName: "",
  isWithDept: false,
  deptPriority: -1,
  nodePriority: 0
});

//部门信息
const deptLayers = ref(0);

//为不能自动绑定数据的el-input绑定数据
const typeNameValue = value => {
  typeName.value = value;
  console.log("审批类型名称", typeName.value);
};
const nodeNameValue = value => {
  nodeName.value = value;
  console.log("审批节点名称", nodeName.value);
};

watch(
  () => processItems.value,
  newVal => {
    console.log("审批项", newVal);
    if (newVal.length > 0) {
      //如果选中的审批项不在可选的审批项中，就把它添加到可选的审批项中
      newVal.forEach((item: string) => {
        if (!processOptions.value.includes(item)) {
          processOptions.value.push(item);
        }
      });
    }
  },
  { deep: true }
);
watch(
  () => deptId.value,
  newVal => {
    if (deptId.value > 5) {
      deptId.value = 5;
    } else if (deptId.value < 0) {
      ElMessage({
        type: "warning",
        message: "不能小于0"
      });
    }
  },
  { deep: true }
);
//暂时添加审批项
const addProcessItems = () => {
  //如果没有选中审批项，直接返回
  if (processItems.value.length === 0) {
    return;
  }
  //把选中的审批项添加到selectedItems中
  processItems.value.forEach((item: string) => {
    if (!selectedItems.value.includes(item)) {
      selectedItems.value.push(item);
    } else {
      ElMessage({
        type: "warning",
        message: "审批项已存在，请重新选择"
      });
      return;
    }
  });
  ElMessage({
    type: "success",
    message: "审批项添加成功"
  });
  //清空选中的审批项
  processItems.value = [];
};
//为审批项添加更复杂的属性
//之后有机会再做
// const handleEdit=(row)=>{
// }
//把选中的审批项删掉
const handleDelete = (index: number) => {
  selectedItems.value.splice(index, 1);
};

//添加审批节点
const addProcessNode = () => {
  //如果没有输入节点名称，直接返回
  if (nodeName.value === "") {
    return;
  }
  //把审批节点添加到processNodes中
  cacheProcessNode.value.nodeName = nodeName.value;
  cacheProcessNode.value.isWithDept = isWithDept.value === "0" ? true : false;
  cacheProcessNode.value.deptPriority = deptId.value;
  cacheProcessNode.value.nodePriority = nodePriority.value;
  //如果节点优先级已经存在，直接返回
  if (
    processNodes.value.some(
      node => node.nodePriority === cacheProcessNode.value.nodePriority
    )
  ) {
    ElMessage({
      type: "warning",
      message: "该节点优先级已存在，请重新输入"
    });
    return;
  }
  const newNode = JSON.parse(JSON.stringify(cacheProcessNode.value));

  processNodes.value.push(newNode);
  console.log("添加审批节点", cacheProcessNode.value);
  //清空审批节点信息
  nodeName.value = "";
  nodePriority.value = nodePriority.value + 1;
  isWithDept.value = "1";
  deptId.value = 0;
  //重新给processNode排序
  processNodes.value.sort((a, b) => a.nodePriority - b.nodePriority);
};
//待被删去的审批节点
const readyForDelete = ref(0);
watch(
  () => readyForDelete.value,
  newVal => {
    console.log("待删除的审批节点", newVal);
  },
  { deep: true }
);
//删除审批节点
const deleteProcessNode = () => {
  console.log("删除审批节点", readyForDelete.value);
  console.log("审批节点:", processNodes.value);
  //如果没有选中审批节点，直接返回
  if (readyForDelete.value === -1) {
    ElMessage({
      type: "warning",
      message: "请选择要删除的审批节点"
    });
    return;
  }
  //把选中的审批节点从processNodes中删除
  let index = processNodes.value.findIndex(
    node => node.nodePriority === readyForDelete.value
  );
  console.log("删除审批节点的索引", index);
  processNodes.value.splice(index, 1);
  console.log("删除审批节点", readyForDelete.value);
  //清空选中的审批节点
  readyForDelete.value = 0;
  processNodes.value.sort((a, b) => a.nodePriority - b.nodePriority);
  console.log("审批节点:", processNodes.value);
};

const addProcessType = async data => {
  const addRes = await addType(data);
  if (addRes.flag === true) {
    ElMessage({
      type: "success",
      message: "审批类型添加成功"
    });
    //清空审批类型信息
    reset();
  } else {
    ElMessage({
      type: "error",
      message: "审批类型添加失败"
    });
  }
};

//保存审批类型
const store = () => {
  //保存审批类型到数据库
  //传入后端的数据应该包括审批类型名称，审批项数组，审批节点数组
  console.log("审批类型名称", typeName.value);
  console.log("审批项", selectedItems.value);
  console.log("审批节点", processNodes.value);
  //如果没有输入审批类型名称，直接返回
  if (typeName.value === "") {
    ElMessage({
      type: "warning",
      message: "审批类型名称不能为空"
    });
    return;
  }
  //如果没有选中审批项，直接返回
  if (selectedItems.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "审批项不能为空"
    });
    return;
  }
  //如果没有添加审批节点，直接返回
  if (processNodes.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "审批节点不能为空"
    });
    return;
  }
  let data = {
    processType: typeName.value,
    applicationItems: selectedItems.value,
    processNodes: processNodes.value
  };
  //添加审批类型到数据库
  addProcessType(data);
  console.log("添加审批类型", data);
};

//重置审批类型
const reset = () => {
  //重置审批类型到初始状态
  typeName.value = "";
  processItems.value = [];
  selectedItems.value = [];
  nodeName.value = "";
  nodePriority.value = 0;
  isWithDept.value = "1";
  deptId.value = 0;
  processNodes.value = [];
  cacheProcessNode.value.nodeName = "";
  cacheProcessNode.value.isWithDept = false;
  cacheProcessNode.value.deptPriority = 0;
  cacheProcessNode.value.nodePriority = 0;
};

const getDeptLayers = async () => {
  //获取部门的层级
  const res = await getTreeHeight();
  if (res.flag === true) {
    deptLayers.value = res.result;
  } else {
    ElMessage({
      type: "error",
      message: "获取部门层级失败"
    });
  }
};

//挂载
onMounted(() => {
  //从数据库拿到部门的最高级
  getDeptLayers();
  //
});
</script>

<style scoped>
.el-style {
  width: 240px;
  margin-left: 10px;
}

.container {
  margin: 1%;
  padding: 1%;
  background-color: rgb(217, 244, 249);
  width: 100%;
  height: 90%;
  border-radius: 5px;
  border: 1px solid white;
  /* 边框 */
  overflow-y: auto;
  /* 当内容超出高度时显示垂直滚动条 */
  overflow-x: hidden;
  /* 隐藏水平滚动条 */
  display: flex;
  flex-direction: column;
}

.container p {
  margin: 1.5%;
  display: flex;
  align-items: center;
}

.concreteBoard {
  /* background-color: pink; */
  width: 100%;
}

.item-button {
  /* background-color: rgb(247, 247, 139); */
  width: 100%;
}
</style>